<template>
  <div class="nav-tree-item-group">
    <div class="nav-tree-item-name">
      <div class="left-side" @click="decide(treeData)">
        <img
          class="icon"
          :src="require('@/assets/oppo/home/folder-icon.svg')"
          alt=""
        />

        <p :class="fontSizeLevel">{{ treeData.displayName }}</p>
      </div>
      <div class="right-side">
        <p class="unreadCount">
          {{
            treeData.unreadItemCount === 0 ||
            id !== undefined ||
            $route.name == "FolderManage"
              ? ""
              : treeData.unreadItemCount
          }}
        </p>
        <div
          class="right-icon-wraper"
          v-if="treeData.childFolderCount"
          @click="toggleTree(treeData.id)"
        >
          <img
            class="right-icon"
            :src="
              isOpen
                ? require('@/assets/oppo/home/list-arrow-up.svg')
                : require('@/assets/oppo/home/list-arrow-down.svg')
            "
            alt=""
          />
        </div>
      </div>
    </div>
    <ul class="nav-tree-item-subTree" v-show="isOpen" v-if="isTree">
      <li v-for="(item, index) in childTree" :key="index">
        <TreeNavItem :treeData="item" :level="newLevel"></TreeNavItem>
      </li>
    </ul>
  </div>
</template>
<script>
import { mapGetters, mapMutations } from "vuex";
import { Dialog } from "vant";
import { isMobile } from "@/utils/helper";
/**
 * 树状导航栏中的一项
 * tree item结构:
 *  普通树：
    {
        name:"title"
    }
    子树：
    {
        name:"subtitle 1",
        subTree:[
            {name:"title 1.1"},
            {name:"title 1.2"}
        ]
    }
 */
export default {
  name: "TreeNavItem",
  data: function () {
    return {
      isOpen: false,
      childTree: [],
      newLevel: 0,
    };
  },
  props: {
    /**
     * 树的数据
     */
    treeData: {
      type: Object,
      // default: [{ displayName: 'title' }]
    },
    level: {
      type: Number,
    },
  },
  computed: {
    ...mapGetters(["checkboxSelectArr", "folderInfo", "isForbidMove"]),
    /**
     * 是树？即非叶子节点
     */
    isTree() {
      return this.treeData.childFolderCount > 0;
    },
    id() {
      return this.$route.params.id;
    },
    fontSizeLevel() {
      return `text-overflow level-${this.level}`;
    },
  },
  methods: {
    ...mapMutations([
      "SAVEMAILTYPE",
      "SAVEFOLDERINFO",
      "SAVECHECKBOXSELECTARR",
    ]),
    /**
     * 数打开与关闭状态的切换
     * 前提非叶子节点
     */
    toggleTree(parentId) {
      if (this.isTree) {
        this.newLevel = this.level + 1;
        console.warn(this.newLevel);
        if (this.newLevel > 3) {
          this.$toast.fail({
            message: this.$lang.openFileConfirm,
            duration: 3000,
          });
          return;
        } else {
          this.isOpen = !this.isOpen;
          if (this.isOpen) {
            this.getChildFolder(parentId);
          }
        }
      } else {
        this.$toast(this.$lang.noSubFolder);
        return;
      }
    },
    decide(treeData) {
      if (
        this.isForbidMove == false &&
        (this.checkboxSelectArr.length > 0 || this.id !== undefined)
      ) {
        Dialog.confirm({
          message: this.$lang.moveFileConfirm(treeData.displayName),
          confirmButtonText: this.$lang.yes,
          cancelButtonText: this.$lang.no,
          className: "errSelfDialog",
        })
          .then(() => {
            this.batchMove(treeData.id);
          })
          .catch(() => {});
        return;
      }
      this.checkboxSelectArr.length === 0;
      if (this.id === undefined) {
        this.goToMailList(treeData.id, treeData.displayName);
      }
    },
    // back() {
    //   if (this.id !== undefined) {
    //     //返回至详情页
    //     this.$router.go(-1);
    //   } else {
    //     //返回至主页
    //     if (isMobile() && window.qing.isSupportNativeJsBridge) {
    //       setTimeout(() => {
    //         window.qing.call("closeWebView");
    //       }, 900);
    //     } else {
    //       this.$router.replace("/home");
    //     }
    //   }
    // },
    //移动邮件后，据王峰解释该邮件会被outlook删除，  直接返回主页算了
    afterMove() {
      if (this.id !== undefined) {
        //从详情页进来 返回至主页 closeWebView
        if (isMobile() && window.qing.isSupportNativeJsBridge) {
          setTimeout(() => {
            window.qing.call("closeWebView");
          }, 900);
        } else {
          this.$router.replace("/home");
        }
      } else {
        //从主页进来的 返回至主页 用go（-1）
        this.$router.go(-1);
      }
    },
    async batchMove(selectedFolderId) {
      this.$toast.loading({
        message: this.$lang.loading,
        forbidClick: true,
        duration: 0,
      });
      let arrIds = [];
      if (this.id !== undefined) {
        arrIds.push(this.id);
      } else {
        arrIds = this.checkboxSelectArr;
      }

      try {
        const res = await this.Api.batchMove({
          folderId: selectedFolderId,
          ids: arrIds,
        });
        const { success } = res?.data;
        if (success) {
          this.$imbedapi(666001004, "moveMail").then((res) =>
            console.warn(res, "邮件移动")
          );
          this.$toast.success(this.$lang.successMove);
          this.showBoxGroup = false;
          this.SAVECHECKBOXSELECTARR([]);
          this.afterMove();
        }
      } catch {
        console.error("批量移动失败");
      }
    },

    /**请求子文件夹 */
    async getChildFolder(parentId) {
      try {
        const res = await this.Api.listChildFolder(parentId);
        const { success, data } = res?.data;
        if (success) {
          console.warn("获取子成功");
          this.childTree = data;
        }
      } catch {
        console.error("获取子文件夹失败");
      }
    },

    goToMailList(folderId, customName) {
      console.warn("子节点执行-----");
      //
      this.SAVEMAILTYPE(customName);
      this.SAVEFOLDERINFO({
        type: customName,
        customName: customName,
        folderId: folderId,
      });
      //深层子组件 要调用 最外层父组件 的方法
      this.$eventBus.$emit("toggleDropdownMenu", {});
      // this.$eventBus.$emit("getMainPageMails", "refresh");
    },
  },
};
</script>
<style lang="less" scoped>
.level-1 {
  font-size: 16px;
}
.level-2 {
  font-size: 14px;
}
.level-3 {
  font-size: 14px;
}
.nav-tree-item-subTree {
  list-style-type: none;
  padding-left: 0;
}
.nav-tree-item-subTree > li {
  margin-bottom: 0.2rem;
  margin-left: 1rem;
}
.nav-tree-item-name {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  line-height: 56px;
  .left-side {
    display: flex;
    align-items: center;
    width: 90%;
    // margin-left: 16px;
  }
  .icon {
    margin-right: 12px;
    pointer-events: none;
  }
  .right-side {
    display: flex;
    align-items: center;
    .unreadCount {
      font-size: 14px;
      color: #969799;
      font-weight: 400;
      margin-right: 8px;
    }
    .right-icon-wraper {
      line-height: 56px;
      img{
        pointer-events: none;
      }
    }
  }
}
.icon-arrow-right {
  display: inline-block;
  position: absolute;
  left: -1rem;
  font-size: 0.5rem;
  color: green;
  font-weight: bolder;
  top: 50%;
  transform: translateY(-50%);
  transition: transform 0.5s;
}
.icon-arrow-right-open {
  transform: translateY(-50%) rotate(90deg);
}
</style>
